package cn.cvs.controller;

import cn.cvs.entity.StorageRecord;
import cn.cvs.entity.Supplier;
import cn.cvs.entity.SysUser;
import cn.cvs.service.StorageRecord.StorageRecordService;
import cn.cvs.service.supplier.SupplierService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.PageSupport;
import com.alibaba.fastjson.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/sys/storageRecord")
public class StorageRecordController {


    @Resource
    private StorageRecordService storageRecordService;
    @Resource
    private SupplierService supplierService;

    /**
     * 根据查询条件分页查询供货单信息
     * @param model
     * @param queryGoodsName
     * @param querySupplierId
     * @param queryPayStatus
     * @param pageIndex
     * @return
     */
    @RequestMapping(value="/list")
    public String list(Model model
            ,@RequestParam(value="queryGoodsName",required=false) String queryGoodsName
            ,@RequestParam(value="querySupplierId",required=false) Integer querySupplierId
            ,@RequestParam(value="queryPayStatus",required=false) Integer queryPayStatus
            ,@RequestParam(value="pageIndex", defaultValue = "1") Integer pageIndex){
        List<Supplier> supplierList = null;
        List<StorageRecord> storageRecordList = null;
        try{
            //设置页面容量
            Integer pageSize = Constants.pageSize;
            //总数量（表）
            int totalCount = 0;
            totalCount = storageRecordService.getCount(queryGoodsName, querySupplierId, queryPayStatus);
            //总页数
            PageSupport pages=new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount = pages.getTotalPageCount();
            //控制首页和尾页
            if(pageIndex > totalPageCount){
                pageIndex = totalPageCount;
            }
            try {
                storageRecordList = storageRecordService.getList(queryGoodsName, querySupplierId, queryPayStatus, pageIndex, pageSize);
                supplierList = supplierService.getList();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            model.addAttribute("storageRecordList", storageRecordList);
            model.addAttribute("supplierList", supplierList);
            model.addAttribute("queryGoodsName", queryGoodsName);
            model.addAttribute("querySupplierId", querySupplierId);
            model.addAttribute("queryPayStatus", queryPayStatus);
            model.addAttribute("totalPageCount", totalPageCount);
            model.addAttribute("totalCount", totalCount);
            model.addAttribute("currentPageNo", pageIndex);
        }catch(Exception e){
            e.printStackTrace();
            return "redirect:/toSysError";
        }
        return "storageRecord/list";
    }

    /**
     * 跳转到添加供货单页面
     * @param storageRecord
     * @return
     */
    @GetMapping("/toAdd")
    public String toAdd(@ModelAttribute("storageRecord") StorageRecord storageRecord){
        return "storageRecord/add";
    }

    /**
     * 添加供货单
     * @param storageRecord
     * @param session
     * @return
     */
    @PostMapping("/add")
    public String add(StorageRecord storageRecord,HttpSession session){
        storageRecord.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        try {
            if(storageRecordService.add(storageRecord)){
                return "redirect:/sys/storageRecord/list";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "storageRecord/add";
    }

    /**
     * 跳转到修改供货单页面
     * @param id
     * @param model
     * @param request
     * @return
     */
    @GetMapping("/toUpdate/{id}")
    public String toUpdate(@PathVariable Integer id,Model model,HttpServletRequest request){
        StorageRecord storageRecord = new StorageRecord();
        try {
            storageRecord = storageRecordService.getById(id);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        model.addAttribute(storageRecord);
        return "storageRecord/update";
    }

    /**
     * 修改供货单
     * @param storageRecord
     * @param session
     * @return
     */
    @PostMapping("/update")
    public String update(StorageRecord storageRecord,HttpSession session){
        storageRecord.setUpdatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());

        try {
            if(storageRecordService.update(storageRecord)){
                return "redirect:/sys/storageRecord/list";
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "storageRecordmodify";
    }



    /**
     * 根据id异步删除供货单信息
     * @param id
     * @return
     */
    @DeleteMapping("/del/{id}")
    @ResponseBody
//    public Object del(@RequestParam(value = "storageRecordId",required = true) Integer storageRecordId){
    public Object del(@PathVariable(value = "id",required = true) Integer id){
        HashMap<String, String> resultMap = new HashMap<String, String>();
        try {
            if(storageRecordService.deleteById(id)){
                resultMap.put("delResult", "true");
            }
            else{
                resultMap.put("delResult", "false");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return JSONArray.toJSONString(resultMap);
    }

    /**
     * 查询供货单详情
     * @param id
     * @param model
     * @param request
     * @return
     */
    @GetMapping("/view/{id}")
    public String view(@PathVariable Integer id,Model model,HttpServletRequest request){
        System.out.println("view id===================== "+id);
        StorageRecord storageRecord = null;
        try {
            storageRecord = storageRecordService.getById(id);
        } catch (Exception e) {
            System.err.println("查询供货单详情");
            e.printStackTrace();
        }
        model.addAttribute(storageRecord);
        return "storageRecord/view";
    }
}
